package com.qq.BFMRSE.BF_MRSEController;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qq.BFMRSE.Cache.indexCacheManager;
import com.qq.BFMRSE.Hdfs.hdfsOper;
import com.qq.BFMRSE.Module.upLoadTool;
import com.qq.BFMRSE.Module.updateTool;
import com.qq.BFMRSE.controllerHelper.updateHelper;
import com.qq.BFMRSE.model.encryptedIndex;
import com.qq.BFMRSE.model.indexTreeNode;
import com.qq.BFMRSE.util.BFConstants;
import com.qq.BFMRSE.util.paraseJsonUtil;

import net.sf.json.JSONObject;

@Controller
public class handlerInsertNewFile {
	@RequestMapping(value= "/addFile",method=RequestMethod.POST)
	public void handler(HttpServletRequest request,HttpServletResponse response){
		 response.setContentType("text/html;charset=utf-8");
	     response.setCharacterEncoding("utf-8");
	     Logger log=Logger.getLogger(handlerInsertNewFile.class);
	    	WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
	    	indexCacheManager cacheInstance=(indexCacheManager) wac.getBean("cacheInstance");//索引缓存
	     int flag=Integer.parseInt(request.getParameter("flag"));
	     String userName=request.getParameter("userName");
	     String fileName=request.getParameter("fileName");
	     String newFileIndexInfo=request.getParameter("newFileIndexInfo");
	     String path=request.getParameter("path");
	     String newFileBitsInfo=request.getParameter("newFileBitsInfo");
	     JSONObject enJo=JSONObject.fromObject(newFileIndexInfo);
	     if(userName!=null&&!"".equals(userName)){
	    	 String indexTreeKey=userName+"-"+BFConstants.INDEXTREEKEY;
	    	 String encIndex=userName+"-"+BFConstants.ENCINDEXKEY;
	    	 Map<String, encryptedIndex>indexMap=null;
	    	 indexTreeNode root=null;
	    	 //首先判断缓存中是否存在索引，如果有从缓存读取，否者从hdfs中读取索引，并加到缓存中
	    	 if(cacheInstance.isContain(indexTreeKey)){
	    		 root=(indexTreeNode) cacheInstance.getCacheData(indexTreeKey);
	        	 log.info("User:"+userName+" read index tree from cacheMap");
	    	 }else{
	    		 root=hdfsOper.readIndexTree(userName+File.separator+BFConstants.SERTREENAME);
	    		 log.info("User:"+userName+" read index tree from hdfs");
	    	 }
	    	 if(cacheInstance.isContain(encIndex)){
	    		 indexMap=(Map<String, encryptedIndex>) cacheInstance.getCacheData(encIndex);
	    		 log.info("User:"+userName+" read encrypted index  from cacheMap");
	    	 }else{
	    		 indexMap=hdfsOper.readEnIndex(userName+File.separator+BFConstants.SERINDEXNAME);
	    		 log.info("User:"+userName+" read encrypted index  from hdfs");
	    	 }
	         encryptedIndex newFileEncryptedIndex=(encryptedIndex) enJo.toBean(enJo, encryptedIndex.class);
	         indexMap.put(fileName, newFileEncryptedIndex);
	         InputStream in=null;
    		 try {
				in=new ByteArrayInputStream(JSONObject.fromObject(indexMap).toString().getBytes(BFConstants.ENCODETYPE));
				upLoadTool ut1=new upLoadTool(userName, BFConstants.UPENCRYPTINDEX, null);
				ut1.upLoadToHdfs(in);
				List<Integer>pathList=paraseJsonUtil.parasePathStack(path);
				List<Integer>newBitSetList=paraseJsonUtil.paraseBitSetString(newFileBitsInfo);
			    if(flag==0)
			     {
			    	  String newTempNodeInfo=request.getParameter("newTempNodeInfo"); 
			    	  JSONObject newTempNodeJo=JSONObject.fromObject(newTempNodeInfo);
			 	     indexTreeNode newTempNode=(indexTreeNode)newTempNodeJo.toBean(newTempNodeJo, indexTreeNode.class);
			 	    // updateHelper.updateNewNode(newTempNode, newBitSetList);
			 	     updateTool udt=new updateTool(userName, pathList, root, newTempNode);
			 	     udt.inUpdateIndexTree(newBitSetList);
			     }else if(flag==1){
			         updateTool udt=new updateTool(userName, pathList, root, null);
			         udt.updateIndexTreeEmptyNode(newBitSetList, fileName);
			     }
			    String tmpDir=ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/")+"tmp";
			     File tmpFile=new File(tmpDir);
			     if(!tmpFile.exists()||!tmpFile.isDirectory()){
			    	 tmpFile.mkdir();
			     }
			     upLoadTool ut2=new upLoadTool(userName, BFConstants.UPENCRYPTTREE, tmpDir);
			     ut2.upLoadToHdfs(root);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
	        
	     }
	}

}
